package com.yuzf.netty.example.bio.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ChatServer {
    private int DEFAULT_PORT = 8888;
    private final String QUIT = "quit";
    private ServerSocket serverSocket;
    private Map<Integer, Writer> connectedClients;

    public ChatServer() {
        connectedClients = new HashMap<>();
    }

    public synchronized void addClient(Socket socket) throws IOException {
        if (socket != null) {
            Integer port = socket.getPort();
            BufferedWriter bfw = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())
            );
            connectedClients.put(port, bfw);
            bfw.write("已连接服务器" + "\n");
            bfw.flush();
            System.out.println("客户端" + port + ":" + "已连接到服务器!!!");


        }
    }

    public synchronized void removeClient(Socket socket) throws IOException {
        if (socket != null) {
            Integer port = socket.getPort();
            if (connectedClients.containsKey(port)) {
                connectedClients.get(port).close();
            }
            connectedClients.remove(port);
            System.out.println("客户端" + port + ":" + "已断开连接!!!");
        }
    }

    public synchronized void forwardMessage(Socket socket, String fwdMsg) throws IOException {
        for (Integer id : connectedClients.keySet()) {
            if (!id.equals(socket.getPort())) {
                BufferedWriter writer = (BufferedWriter) connectedClients.get(id);
                writer.write("客户端"+socket.getPort()+":"+fwdMsg+"\n");
                writer.flush();
            }
        }
    }

    public synchronized void close() {
        if (this.serverSocket != null) {
            try {
                this.serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public boolean readForQuit(String msg) {
        return QUIT.equals(msg);
    }

    public void start() {
        try {
            serverSocket = new ServerSocket(DEFAULT_PORT);

            System.out.println("服务器已启动，正在监听端口" + DEFAULT_PORT);

            while (true) {
                Socket socket = serverSocket.accept();
                //创建处理线程
                new Thread(new ChatHandler(this, socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    public static void main(String[] args) {
        ChatServer chatServer = new ChatServer();
        chatServer.start();
    }
}
